package com.dci.intellij.dbn2.browser;

import com.dci.intellij.dbn.browser.DatabaseBrowserManager;
import com.dci.intellij.dbn.browser.ui.BrowserToolWindowForm;
import com.dci.intellij.dbn.common.Icons;
import com.dci.intellij.dbn.common.latent.Latent;
import com.dci.intellij.dbn.common.latent.RuntimeLatent;
import com.dci.intellij.dbn2.utils.ReflectionUtils;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentFactoryImpl;
import org.jetbrains.annotations.NotNull;

public class DatabaseBrowserToolWindowFactory extends com.dci.intellij.dbn.browser.DatabaseBrowserToolWindowFactory {
    private RuntimeLatent<BrowserToolWindowForm> toolWindowForm = null;

    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        spy(project);

        BrowserToolWindowForm toolWindowForm = DatabaseBrowserManager.getInstance(project).getToolWindowForm();
        ContentFactory contentFactory = new ContentFactoryImpl();
        Content content = contentFactory.createContent(toolWindowForm.getComponent(), (String)null, true);
        toolWindow.getContentManager().addContent(content);
        toolWindow.setIcon(Icons.WINDOW_DATABASE_BROWSER);
    }

    private void spy(Project project) {
        DatabaseBrowserManager browserManager = DatabaseBrowserManager.getInstance(project);
        toolWindowForm = Latent.disposable(browserManager, () -> {
            return new com.dci.intellij.dbn2.browser.ui.BrowserToolWindowForm(project);
        });
        ReflectionUtils.setFieldValue(browserManager, "toolWindowForm", toolWindowForm);
    }
}
